<?php


namespace App\Http\Controllers\Api;

use App\Bus\AuthBus;
use App\Constant\CacheConstant;
use App\Constant\FrontendConstant;
use App\Exceptions\ApiV2Exception;
use App\Exceptions\ServiceException;
use App\Services\Base\Interfaces\CacheServiceInterface;
use App\Services\Other\Models\WechatPlatform;
use Doctrine\DBAL\Exception\ServerException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Services\Member\Services\UserService;
use App\Services\Member\Interfaces\UserServiceInterface;
use Illuminate\Pagination\LengthAwarePaginator;
use App\Http\Controllers\Api\Traits\ResponseTrait;

class BaseController
{
    use ResponseTrait;

    protected $guard = FrontendConstant::API_GUARD;

    protected $user;
    protected $companyId;


    /**
     * @param string $message
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function success($message = '')
    {
        return response()->json([
            'code' => 0,
            'message' => $message,
            'data' => [],
        ]);
    }

    /**
     * @param array $data
     * @param string $message
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function successData($data = [], $message = '')
    {
        return response()->json([
            'code' => 0,
            'message' => $message,
            'data' => $data,
        ]);
    }

    /**
     * @param $message
     * @param int $code
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function error($message, $code = 1)
    {
        return response()->json([
            'code' => $code,
            'message' => $message,
            'data' => [],
        ]);
    }

    /**
     * 检测是否登录
     *
     * @return boolean
     */


    /**
     * @param $user
     * @return mixed
     * @throws ServiceException
     */
    protected function token($user)
    {

        try {
            if ((int)$user['is_lock'] === 1) {
                throw new ServiceException(__('用户已锁定无法登录'));
            }

        } catch (ServerException $e) {
            return $this->error($e->getMessage());
        }


        /**
         * @var AuthBus $authBus
         */
        $authBus = app()->make(AuthBus::class);

        return $authBus->tokenLogin($user['id'], get_platform());
    }
    protected function check(): bool
    {
        return Auth::guard($this->guard)->check();
    }

    /**
     * 登录用户的id
     * @return int
     */
    protected function id()
    {
        return Auth::guard($this->guard)->id();
    }

    /**
     * 用户登录信息
     * @return array
     */
    protected function user()
    {
        if (!$this->user) {
            /**
             * @var $userService UserService
             */
            $userService = app()->make(UserServiceInterface::class);
            $this->user = $userService->find($this->id(), ['role']);
        }
        return $this->user;
    }

    /**
     * @param $list
     * @param $total
     * @param $page
     * @param $pageSize
     *
     * @return LengthAwarePaginator
     */
    protected function paginator($list, $total, $page, $pageSize)
    {
        return new LengthAwarePaginator($list, $total, $pageSize, $page, ['path' => request()->path()]);
    }

    /**
     * @throws ApiV2Exception
     */
    protected function mobileCodeCheck()
    {
        $mobile = request()->input('mobile');
        $mobileCode = request()->input('mobile_code');

        if (mobile_code_check($mobile, $mobileCode) === false) {
            throw new ApiV2Exception(__('短信验证码错误'));
        }
    }

    public function downFile(string $url, string $file_name)
    {
        header('Content-Description: File Transfer');
        header('Content-Type: application/vnd.android.package-archive');
        header('Content-Disposition: attachment; filename=' . $file_name);
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
        curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $buffer) {
            echo $buffer;
            return strlen($buffer);
        });
        curl_exec($ch);
        curl_close($ch);
    }
    public function getCompanyId($id)
    {
        if (is_numeric($id)) {
            return $id;
        }
        $cacheService = app()->make(CacheServiceInterface::class);
        $cacheKey = get_cache_key(CacheConstant::WECHAT_MINI_APP['name'], $id);
        if ($cacheService->has($cacheKey)) {
            return $cacheService->get($cacheKey);
        }
        $mini = WechatPlatform::query()->where('app_id', $id)->first();
        $companyId = $mini['company_id'] ?? 1;
        $cacheService->put(get_cache_key(CacheConstant::WECHAT_MINI_APP['name'], $id), $companyId, CacheConstant::WECHAT_MINI_APP['expire']);
        return $companyId;

    }


}
